<?php

namespace App\Http\Models\Student;

use App\Common\Utils\Common;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Student\Student;
use App\Http\Models\Student\StudentBuy;
use App\Http\Models\Dances\Dances;

class StudentService
{

    public function index($request)
    {
        $studentDatas = Student::select()
            ->where('nickname', 'like', '%' . $request->name . '%')
            ->orderBy('created_at', 'desc')
            ->paginate(PAGES);
        foreach ($studentDatas as $key => $val) {
            $studentDatas[$key]->created_at = date("Y-m-d H:i:s", $val->created_at);
        }
        return $studentDatas;
    }

    //获取课程列表
    public function getDances()
    {
        $where = [
            'status' => 0,
            'types'  => 1
        ];
        return (new Dances())->getDatesTime($where);
    }

    public function getLeagueDances()
    {
        $where = [
            'status' => 0,
            'types'  => 0
        ];
        return (new Dances())->getDatesTime($where);
    }

    public function updateSave($request, $id)
    {
        if ($request->vips == 1) {
            $data = [
                'member_status' => 1
            ];
            $res = Student::where('id', decryptUrl($id))->update($data);
        }

        $danceId = 0;
        if($request->status==0){
            if ($request->league) {
                $danceId = $request->league;
            }
        }
        if($request->status==1){
            if ($request->sijiao) {
                $danceId = $request->sijiao;
            }
        }

        $data = [
            'student_id'    => decryptUrl($id),
            'member_number' => $request->member_number,
            'stu_status'    => $request->status,
            'amount'        => $request->amount,
            'teacher_id'    => $danceId,
            'begin_time'    => $request->begin_time ? strtotime($request->begin_time) : 0,
            'end_time'      => $request->end_time ? strtotime($request->end_time) : 0,
            'created_at'    => time()
        ];
        try {
            $res = StudentBuy::create($data);
            if ($res) {
                Common::success(UPDATE_SUCCES);
                return $res;
            } else {
                Common::error(UPDATE_ERROR);
            }
        } catch (Exception $ex) {
            Common::error(UPDATE_ERROR);
        }
    }

    public function show($id)
    {
        return Student::where('id', decryptUrl($id))->first();
    }

    public function getBuyLog($id)
    {
        return StudentBuy::where('student_id', decryptUrl($id))->orderBy('created_at', 'desc')->get()->all();
    }

    //删除购买记录
    public function buyLogDelete($id)
    {
        return StudentBuy::where('id', decryptUrl($id))->delete();
    }

}
